package com.common.base.app.activity

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.app.viewmodel.ListViewModel
import com.common.base.utils.LayoutManagerUtil
import com.common.base.widget.IRecyclerView
import com.common.base.widget.PlaceholderView
import java.util.concurrent.CopyOnWriteArrayList

/**
 * 列表基类
 */
abstract class BaseRecyclerVMActivity<VB : ViewBinding, VM : ListViewModel<K>, K> :
    BaseVMActivity<VB, VM>() {
    //当前适配器
    var mAdapter: BaseQuickAdapter<K, BaseViewHolder>? = null

    //数据源
    var mData = CopyOnWriteArrayList<K>()

    //取得适配器
    abstract fun getAdapter(): BaseQuickAdapter<K, BaseViewHolder>

    //占位控件
    override fun getPlaceholderView(): PlaceholderView? = mViewBinding.mPlaceholderView

    final override fun initViews() {
        super.initViews()
        //是否添加头部
        val headView = addHeadView()
        if (headView != 0) {
            getHeadLayout()?.addView(layoutInflater.inflate(headView, null))
        }
        val contentView = addContentView()
        if (contentView != 0) {
            getContentLayout()?.addView(layoutInflater.inflate(contentView, null))
        }
        //获取适配器
        mAdapter = getAdapter()
        getIRecyclerView().setAdapter(mAdapter)
        getIRecyclerView().setOnLoadMoreListener { onLoadMoreListener() }
        getIRecyclerView().setOnRefreshListener { onRefreshListener() }
        initRecyclerView()
        initView()
        showLoading()
    }

    open fun getHeadLayout(): ViewGroup? = null

    open fun getContentLayout(): ViewGroup? = null

    override fun initEvents() {
        setErrorRetryListener { lazyInitData() }
    }

    override fun lazyInitData() {
        super.lazyInitData()
        (needAutoRefresh() && !isEnablePureScrollMode()).yes {
            autoRefresh()
        }.otherwise { loadData() }
    }

    fun loadData() {
        mViewModel.loadData(getIRecyclerView().getPage(), getListExtParam()).observe(this) {
            showData(it.Data, it.hasMore)
        }
    }


    //初始化列表控件
    private fun initRecyclerView() {
        getIRecyclerView().setItemDivider(getItemDivider())
        getIRecyclerView().setLayoutManager(getLayoutManager())
        getIRecyclerView().setRefreshHeader(getRefreshHeader())
        getIRecyclerView().setRefreshFooter(getRefreshFooter())
        getIRecyclerView().setIsEnableAutoLoadMore(isEnableAutoLoadMore())
        getIRecyclerView().setIsEnableLoadMore(isEnableLoadMore())
        getIRecyclerView().setIsEnableRefresh(isEnableRefresh())
        getIRecyclerView().setIsEnablePureScrollMode(isEnablePureScrollMode())
        getIRecyclerView().setIsEnableOverScrollBounce(isEnableOverScrollBounce())
        getIRecyclerView().setIsEnableFooterFollowWhenNoMoreData(isEnableFooterFollowWhenNoMoreData())
        getIRecyclerView().setIsShowShadowView(isShowShadowView())
        getIRecyclerView().initViewParams()
    }

    override fun autoRefresh() {
        getIRecyclerView().autoRefresh()
    }

    open fun showData(data: List<K>?, hasMore: Boolean) {
        //如果是第一页则清除数据、翻页则不清除自动累计
        getIRecyclerView().isFirstPage().yes {
            mData.clear()
        }
        data?.let { mData.addAll(it) }
        mAdapter?.setList(mData)
        mAdapter?.notifyDataSetChanged()
        //如果数据为空则显示空白占位图
        getIRecyclerView().hideRefreshing(hasMore)
        if (mData.isEmpty()) {
            showEmpty()
        } else {
            showContent()
        }
    }

    /**
     * 列表请求额外参数
     */
    protected open fun getListExtParam(): Any? = null

    //获取当前列表数据
    protected fun getData(): List<K> {
        return mData
    }

    //是否需要自动下拉刷新
    open fun needAutoRefresh(): Boolean {
        return false
    }

    //添加头部
    open fun addHeadView(): Int {
        return 0
    }

    //添加内容区域布局
    open fun addContentView(): Int {
        return 0
    }

    //取得列表对象
    abstract fun getIRecyclerView(): IRecyclerView

    override fun getRecyclerView(): RecyclerView? {
        return getIRecyclerView().getRecyclerView()
    }

    open fun initView() {}

    //加载更多
    override fun onLoadMoreListener() {
        loadData()
    }

    //下拉刷新
    override fun onRefreshListener() {
        super.onRefreshListener()
        mData.clear()
        loadData()
    }

    override fun showLoading() {
        if (getIRecyclerView().getPage() == 1) {
            super.showLoading()
        }
    }

    override fun showError(msg: String?) {
        super.showError(msg)
        getIRecyclerView().hideRefreshing(false)
    }

    //显示页面空白
    override fun showEmpty(msg: String?) {
        if (getIRecyclerView().getPage() == getIRecyclerView().getStartPage()) {
            super.showEmpty(msg)
        } else {
            // 如果不是第一页，并且没有数据了，就不结束加载更多
            getIRecyclerView().hideRefreshing(false)
        }
    }

    /**
     * 生成分割线
     */
    open fun getItemDivider(): RecyclerView.ItemDecoration? {
        return null
    }

    /**
     * 子类生成布局管理器
     */
    open fun getLayoutManager(): RecyclerView.LayoutManager {
        return LayoutManagerUtil.getVerticalLinearLayoutManager(this)
    }

    //是否显示列表顶部阴影
    open fun isShowShadowView(): Boolean = false

}